<?php
class Message extends AppModel {
	public $name = 'Message';
	public $tablePrefix = 'cakeforum_';

	public $belongsTo = array(
		'User',
		'Unread' => array(
			'counterCache' => true,
			'foreignKey' => 'user_id',
			'className' => 'User',
			'fields' => 'message_count',
			'counterScope' => array('Message.viewed' => 1)

		),
		'To' => array(
			'foreignKey' => 'to_user_id',
			'className' => 'User',
			'fields' => 'username',
		),
		'From' => array(
			'foreignKey' => 'from_user_id',
			'className' => 'User',
			'fields' => 'username'
	));

	public $validate = array(
		'to' => array(
			'required' => array(
				'rule' => 'notEmpty',
				'message' => 'Please enter a username'
			),
			'required' => array(
				'rule' => array('userExists'),
				'message' => 'That user doesn\'t exist'
			)
		),
		'title' => array(
			'rule' => 'notEmpty',
			'message' => 'Please enter a title'
		),
		'body' => array(
			'rule' => 'notEmpty',
			'message' => 'Please enter a message'
		)
	);

	function userExists($username){
		return $this->User->userExists($username['to']);
	}


	public function isOwnedBy($messageId){
		return $this->field('id', array('id' => $messageId, 'user_id' => AuthComponent::User('id'))) == $messageId;
	}
}